package com.app.utils;

import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.Iterator;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class StringUtil
{
    public static boolean isNumeric(final String str) {
        final Pattern pattern = Pattern.compile("[0-9]*");
        final Matcher isNum = pattern.matcher(str);
        return isNum.matches();
    }
    public static String replaceBlank(String str) {
        String dest = "";
        if (str!=null) {
            Pattern p = Pattern.compile("\\s*|\t|\r|\n");
            Matcher m = p.matcher(str);
            dest = m.replaceAll("");
        }
        return dest;
    }
    /* 将map对象参数转换成String=String&方式

     * @param params(参数)

     * @param charset(编码格式)

     * @return

     * @throws UnsupportedEncodingException

     */

    public static String generateParams(Map<String, String> params, String charset) throws UnsupportedEncodingException {

        int flag=0;

        StringBuffer ret=new StringBuffer();

        Iterator iter = params.entrySet().iterator();

        while (iter.hasNext()) {

            Map.Entry entry = (Map.Entry) iter.next();

            Object key = entry.getKey();

            Object val = entry.getValue();

            if(val!=null){

                if(flag==0){

                    ret.append(key);

                    ret.append("=");

                    if(charset!=null&&!charset.equals("")){

                        try {
                            ret.append(URLEncoder.encode(val.toString(), charset));
                        } catch (UnsupportedEncodingException e) {
                            e.printStackTrace();
                        }

                    }else{

                        ret.append(val.toString());

                    }

                    flag++;

                }else{

                    ret.append("&");

                    ret.append(key);

                    ret.append("=");

                    if(charset!=null&&!charset.equals("")){

                        ret.append(URLEncoder.encode(val.toString(), charset));

                    }else{

                        ret.append(val.toString());

                    }

                }

            }

        }

        return ret.toString();

    }

}
